var app = getApp();
var custId = app.globalData.custID;
var time;
var common = require("../../utils/Conmon.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    popin: false,
    orderId: "",
    list: [],
    paymentList: [],
    payMoney: '0.00',
    payType: -1,
    clickNum: 0,
    msg: "",
    createTime: new Date(),
    timeMin: 0,   //倒计时时间
    unionShopID: 0,  //店铺id
    payTypeId: 0
  },
  changePopin: function () {
    this.setData({
      popin: !this.data.popin
    });
  },
  //取消订单
  cancelOrder: function (e) {
    var that = this;
    wx.showModal({
      content: "确定取消该订单吗？",
      showCancel: true,
      confirmText: "确定",
      success: function (res) {
        if (res.confirm) {
          wx.showToast({
            title: '加载中...',
            icon: 'loading'
          })
          wx.request({
            url: app.globalData.apiurl + '/mobile/api/OrderInfo/CancelOrder',
            data: { custId: custId, userId: wx.getStorageSync('UserInfo').UserID, orderId: that.data.orderId, reason: "未支付，临时取消" },
            header: {
              'X_ManuName': app.globalData.manuName
            },
            method: 'GET',
            success: function (res) {
              wx.hideToast();
              if (res.data.code == 1200) {
                wx.showToast({
                  title: '取消成功',
                  icon: 'success',
                  duration: 2000
                })
                wx.switchTab({
                  url: '/pages/myorders/myorders'
                })
              } else {
                wx.showModal({
                  content: "取消失败",
                  showCancel: false,
                  confirmText: "确定"
                })
              }
            }
          })
        }
      }
    })
  },
  //去付款
  gopay: function (e) {
    var that = this;
    if (that.data.clickNum == 0) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      });

      that.setData({
        clickNum: 1
      })
      var payTypeId = that.data.payTypeId;
      if (payTypeId == 0) {
        wx.showModal({
          content: '请选择支付方式',
          showCancel: false,
          confirmText: "确定"
        })
        that.setData({
          clickNum: 0
        })
        return;
      }
      var openid = wx.getStorageSync('openId');

      if (that.data.payType != 5) {
        wx.request({
          url: app.globalData.apiurl + '/mobile/api/OrderForm/GoPay3',
          data: { CustId: custId, OrderId: that.data.orderId, OpenId: openid, PayTypeId: payTypeId },
          method: 'GET',
          header: {
            'X_ManuName': app.globalData.manuName
          },
          success: function (res) {
            wx.hideLoading();
            if (res.data.code == 1200) {
              var jsonStr = JSON.parse(res.data.content);
              wx.requestPayment({
                'timeStamp': jsonStr.timeStamp,
                'nonceStr': jsonStr.nonceStr,
                'package': jsonStr.package,
                'signType': jsonStr.signType,
                'paySign': jsonStr.paySign,
                'success': function (res) {
                  that.setData({
                    clickNum: 0
                  })
                  callBack(that);
                },
                'fail': function (res) {
                  console.log(res);
                  that.setData({
                    clickNum: 0
                  })
                },
                'complete': function (res) {
                  console.log(res);
                }
              });
            } else {
              that.setData({
                clickNum: 0
              })
              wx.showModal({
                content: res.data.msg,
                showCancel: false,
                confirmText: "确定"
              })
              that.setData({
                popin: false
              })
            }
          },
          fail: function (res) {
            wx.hideLoading();
            that.setData({
              clickNum: 0
            })
          }
        })
      } else {
        //余额支付
        wx.request({
          url: app.globalData.apiurl + '/mobile/api/OrderForm/BlancePay2',
          data: { CustId: custId, OrderId: that.data.orderId, UserId: wx.getStorageSync('UserInfo').UserID },
          method: 'GET',
          header: {
            'X_ManuName': app.globalData.manuName
          },
          success: function (res) {
            wx.hideLoading();
            if (res.data.code == 1) {
              //支付成功
              wx.showModal({
                content: '支付成功',
                showCancel: false,
                confirmText: "确定"
              });
              wx.switchTab({
                url: '/pages/myorders/myorders',
              });
            } else {
              that.setData({
                clickNum: 0
              })
              wx.showModal({
                content: res.data.msg,
                showCancel: false,
                confirmText: "确定"
              });
            }
          },
          fail: function (res) {
            wx.hideLoading();
            that.setData({
              clickNum: 0
            });
          }
        });
      }
    }
  },
  //付款方式
  changePaytype: function (e) {
    var paylist = this.data.paymentList;
    for (var i = 0, len = paylist.length; i < len; i++) {
      if (paylist[i].PayTypeID == e.currentTarget.id) {
        paylist[i].checked = true;
      } else {
        paylist[i].checked = false;
      }
    }
    this.setData({
      payType: e.currentTarget.dataset.paytype,
      payTypeId: e.currentTarget.id,
      paymentList: paylist
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    common.pageInit( function () {
    });
    this.setData({
      orderId: options.OrderID,
      unionShopID: options.unionShopID,
      clickNum: 0
    })

    LoadOrderInfo(this);
    LoadPayment(this);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('离开页面');
    clearTimeout(time);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

//加载订单信息
function LoadOrderInfo(that) {
  wx.showLoading({
    title: '加载中...',
    mask: true
  });
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/OrderInfo/GetOrderByOrderId',
    data: { custId: custId, orderId: that.data.orderId, unionShopID: that.data.unionShopID },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function (res) {
      wx.hideLoading();
      clearTimeout(time);
      if (res.data.code == 1200) {
        var list = res.data.content;
        that.setData({
          list: list,
          payMoney: list.PayAmount.toFixed(2)
        })
        if (list.OrderSet != null && list.OrderSet != undefined) {
          if (list.OrderSet.IsNodeEnable && list.OrderSet.IsOrderAutoCancelTimeEnable && parseInt(list.OrderSet.OrderAutoCancelTime) > 0) {
            that.setData({
              timeMin: parseInt(list.OrderSet.OrderAutoCancelTime),
              msg: "请在0分0秒内完成支付，超时订单自动取消",
              createTime: list.CreateTime
            });
            countdown(that);
          }
        }
      } else {
        console.log('加载失败');
      }
    }
  })
}

//加载支付方式
function LoadPayment(that) {
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/OrderForm/GetPayTypeListByTerminal',
    data: { custId: custId, useTerminal: 3 },
    header: {
      'X_ManuName': app.globalData.manuName
    },
    method: 'GET',
    success: function (res) {
      if (res.data.code == 1200) {
        var paylist = res.data.content;
        if (paylist != null && paylist.length > 0) {
          for (var i = 0, len = paylist.length; i < len; i++) {
            if (i == 0) {
              paylist[i].checked = true;
              that.setData({
                payType: paylist[i].PayType,
                payTypeId: paylist[i].PayTypeID,
              })
            } else {
              paylist[i].checked = false;
            }
          }
        }
        that.setData({
          paymentList: paylist
        });
      } else {
        console.log('加载失败');
      }
    }
  })
}

function countdown(that) {
  var timeMin = that.data.timeMin;
  var createTime = that.data.createTime;
  var EndTime = newDate(createTime); //截止时间
  var summinute = EndTime.getMinutes() + timeMin;
  if (summinute > 60) {
    var hour = Math.floor(summinute / 60);
    var rest = summinute % 60;
    EndTime.setHours(EndTime.getHours() + hour);
    EndTime.setMinutes(rest);
  } else {
    EndTime.setMinutes(summinute);
  }
  var NowTime = new Date();
  var t = EndTime.getTime() - NowTime.getTime();
  if (t > 0) {
    var h = Math.floor(t / 1000 / 60 / 60);
    var m = Math.floor(t / 1000 / 60 % 60);
    var s = Math.floor(t / 1000 % 60);
    if (h > 0) {
      m = h * 60 + m;
    }
    time = setTimeout(function () {
      that.setData({
        msg: "请在" + m + "分" + s + "秒内完成支付，超时订单自动取消",
      });
      countdown(that);
    }, 1000);
  } else {
    clearTimeout(time);
    that.setData({
      msg: "订单超时未支付,已取消"
    });
    wx.request({
      url: app.globalData.apiurl + '/mobile/api/OrderInfo/CancelOrder',
      data: { custId: custId, userId: wx.getStorageSync('UserInfo').UserID, orderId: that.data.orderId, reason: "超时未支付,已取消" },
      header: {
        'X_ManuName': app.globalData.manuName
      },
      method: 'GET',
      success: function (res) {
        if (res.data.code == 1200) {
          wx.switchTab({
            url: '/pages/myorders/myorders'
          })
        }
      }
    });
  }
}

//支付回调
function callBack(that) {
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/OrderForm/SmallPayCompleteCallBack',
    data: { custId: custId, payNo: that.data.orderId },
    header: {
      'X_ManuName': app.globalData.manuName
    },
    method: 'GET',
    success: function (res) {
      if (res.data.code == 1200) {
        wx.redirectTo({
          url: '/pages/paySucceed/paySucceed?Total_fee=' + res.data.content
        });
      } else {
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          confirmText: "确定"
        })
      }
    }
  })
}


function newDate(strdate) {
  var arr = strdate.split(/[- : \/]/);
  var date = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
  return date;
} 